﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace RuoYi.Test;

public class TestBase
{
    public ILogger Logger { get; private set; }
    protected IServiceScope TestServiceScope { get; }
    protected IServiceProvider ServiceProvider { get; set; }

    public TestBase()
    {
        IHost host = Host.CreateDefaultBuilder()
           //.UseAutofac()
           .ConfigureServices((host, service) =>
           {
               ConfigureServices(host, service);
               service.AddLogging(builder => builder.ClearProviders().AddConsole().AddDebug());
               /*application= */
               //service.AddApplicationAsync<YiAbpTestModule>().Wait();
           })
           .ConfigureAppConfiguration(this.ConfigureAppConfiguration)
           .Build();

        this.ServiceProvider = host.Services;
        this.TestServiceScope = ServiceProvider.CreateScope();
        this.Logger = (ILogger)this.ServiceProvider.GetRequiredService(typeof(ILogger<>).MakeGenericType(this.GetType()));

        host.Run();
    }


    public virtual void ConfigureServices(HostBuilderContext host, IServiceCollection service)
    {
        // Configure<AbpBackgroundWorkerQuartzOptions>(options =>
        // {
        //     options.IsAutoRegisterEnabled = false;
        // });
        //service.Configure<AbpBackgroundWorkerOptions>(options =>
        //{
        //    options.IsEnabled = false; //禁用作业执行
        //});
        //service.Configure<DbConnOptions>(options =>
        //{
        //    options.Url = $"DataSource=yi-rbac-test-{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.db";
        //});
    }
    protected virtual void ConfigureAppConfiguration(IConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.AddJsonFile("appsettings.json");
    }

    protected virtual T? GetService<T>()
    {
        return ServiceProvider.GetService<T>();
    }

    protected virtual T GetRequiredService<T>() where T : notnull
    {
        return ServiceProvider.GetRequiredService<T>();
    }

    protected virtual T? GetKeyedServices<T>(object? serviceKey)
    {
        return ServiceProvider.GetKeyedService<T>(serviceKey);
    }

    protected virtual T GetRequiredKeyedService<T>(object? serviceKey) where T : notnull
    {
        return ServiceProvider.GetRequiredKeyedService<T>(serviceKey);
    }
}